package com.java.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author jl
 * Created on 2020/9/27
 */
public class NIOClient {

    public static void main(String[] args) throws Exception {
        // 创建socketChannel
        SocketChannel socketChannel = SocketChannel.open();
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        // 设置服务器端的ip 和 端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        // 连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间，客户端不会阻塞，可以做其它工作..");
            }
        }
        // 连接成功,发送数据
        String str = "hello, netty~";
        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        // 将byteBuffer写入channel
        socketChannel.write(byteBuffer);
    }
}
